<?php
namespace app\common\model;
class Wallet extends \think\Model
{
    protected $resultSetType = 'collection';
    public function message(){
        return $this->hasOne('message','id','message_id');
    }
    public function account(){
        return $this->hasOne('account','id','account_id');
    }
    //关联跟进信息
    public function followInfo()
    {
        return $this->hasMany('Follow','message_id','message_id')->order('date desc');
    }
    //关联上传凭证信息
    public function dealInfo()
    {
        return $this->hasMany('Deal','message_id','message_id');
    }
    //转介信息
    public function transferInfo(){
        return $this -> hasOne('transfer','message_id','message_id');
    }

    /**
     * @param string id 用户id
     * @param string amount 金额
     * @return array
     */
    public function inserts(){
        $data = input('param.');
        if (!$data['id'])
            return [
                'message' => '用户不能为空'
            ];
        $userInfo = \app\common\model\Message::with('buildingInfo')->where('id',$data['id'])->find();
        if ($userInfo['status'] =='已买')
            return [
                'message' => '该用户已结佣'
            ];
        if ($userInfo['status'] != '已定')
            return [
                'message' => '只有已定用户才能结佣'
            ];
        if (!$data['amount'])
            return [
                'message' => '成交金额不能为空'
            ];
        $addData = [];
        $buildingPoint = \app\common\model\BuildingPoint::where('building_id',$userInfo['building'])->select()->toArray();
        if (empty($buildingPoint) == true)
            return [
                'message' => '该楼盘点位未设置'
            ];
        //是否有转介判定最终成交人
        if ($userInfo['transferInfo']){
            $agentInfo = $userInfo['transferInfo']['accountInfo'];

            //判断转介人是否是全民经纪人
            if($userInfo['accountInfo']['role'] =='33'){
                $point = $this -> point($buildingPoint,'action','4');
                //下线提成
                if ($point)
                    $addData[] = [
                        'account_id' => $userInfo['accountInfo']['id'],
                        'count' => $point[1]=='%'?$data['amount']*$point[0]*0.01:$point[0],
                        'description' => '全民经纪人下线提成'
                    ];
                $point = $this -> point($buildingPoint,'action','3');
                //上线提成
                if ($point)
                    //判断最终成交人是否是上线
                    if ($agentInfo['id'] != $userInfo['accountInfo']['higher']['a_id'])
                        $addData[] = [
                            'account_id' => $userInfo['accountInfo']['higher']['a_id'],
                            'count' => $point[1]=='%'?$data['amount']*$point[0]*0.01:$point[0],
                            'description' => '全民经纪人上线提成'
                        ];

            }
            else{
                $addData = array_merge($addData,$this -> transfer($userInfo['accountInfo'],$agentInfo,$buildingPoint,$data['amount']));
            }
        }
        else{
            $agentInfo = $userInfo['accountInfo'];
        }



        //获取成交经纪人的所有上级
        $check = $agentInfo;
        while($check){
            $check = $check->higher;
            if ($check)
                $higher[] = \app\common\model\Account::field('id,role')->find($check['a_id'])->toArray();
        }

        foreach ($higher as $value){
            //一级渠道
            if (in_array($value['role'],['30','21','15'])){
                $point = $this -> point($buildingPoint,'action',1);
                if ($point)
                    $step1 = [
                        'account_id' => $value['id'],
                        'count' => $point[1]=='%'?$data['amount']*$point[0]*0.01:$point[0],
                    ];
                //渠道公司兑应渠道经理提成
                if ($value['role'] =='15'){
                    $qudao = \app\common\model\Account::where([
                        'project' => $userInfo['building']
                    ])->find();
                    if ($qudao){
                        $point = $this -> point($buildingPoint,'role',14);
                        if ($point)
                            $addData[] = [
                                'account_id' => $qudao['id'],
                                'count' => $point[1]=='%'?$data['amount']*$point[0]*0.01:$point[0],
                            ];
                    }
                }
            }
            elseif ($value['role'] =='24'){
                $point = $this -> point($buildingPoint,'action',2);
                if ($point)
                    $step2 = [
                        'account_id' => $value['id'],
                        'count' => $point[1]=='%'?$data['amount']*$point[0]*0.01:$point[0],
                    ];
            }
        }

        //代理
        if (!$step1){
            //成交经纪人提成
            $point = $this -> point($buildingPoint,'role',$agentInfo['role']);
            if ($point)
                $addData[] = [
                    'account_id' => $agentInfo['id'],
                    'count' => $point[1]=='%'?$data['amount']*$point[0]*0.01:$point[0],
                    'description' => '用户成交提成'
                ];
            foreach ($higher as $value){
                $point = $this -> point($buildingPoint,'role',$value['role']);
                if ($point)
                    $addData[] = [
                        'account_id' => $value['id'],
                        'count' => $point[1]=='%'?$data['amount']*$point[0]*0.01:$point[0],
                        'description' => '用户成交提成'
                    ];
            }
        }
        //渠道
        else{
            //二级渠道存在
            if ($step2){
                $addData[] = [
                    'account_id' => $step2['account_id'],
                    'count' => $step2['count'],
                    'description' => '二级渠道公司提成'
                ];
                $step1['count'] -= $step2['count'];
                if ($step1['count'] < 0)
                    $step1['count'] = '0';
            }

            //一级渠道
            $addData[] = [
                'account_id' => $step1['account_id'],
                'count' => $step1['count'],
                'description' => '渠道公司提成'
            ];
        }

        foreach ($addData as $k=> $value){
            $addData[$k]['message_id'] = $data['id'];
            $addData[$k]['status'] = '0';
            $addData[$k]['date'] = time();
        }



        $this -> saveAll($addData);

        //更新用户状态为已买
        \app\common\model\Message::where('id', $data['id'])
            ->update([
                'status' => '已买',
                'price_end' => $data['amount']
            ]);
        //插入一条跟进
        \app\common\model\Follow::create([
            'content'  =>  '已成交',
            'date' =>  time(),
            'account_id' => '2',
            'message_id' => $data['id']
        ]);

        //发送小程序通知
        if ($addData){
            $WxMini =new \app\common\logic\WxMini();
            foreach ($addData as $value){
                $open_id = \app\common\model\Account::where('id',$value['account_id'])->find()->open_id;
                if ($open_id){
                    $sendData = [
                        'keyword1' => ['value' => $userInfo['building_info']['name']],
                        'keyword2' => ['value' => date('Y-m-d H:i:s')],
                        'keyword3' => ['value' => $value['count'].'元'],
                        'keyword4' => ['value' => '客户姓名:'.$userInfo['name'].'; 电话号码:'.$userInfo['telephone'].' ;成交房号:'.$userInfo['number']],
                    ];
                    $WxMini -> sendNotify($open_id,1,'pages/finance/finance',$sendData);
                }
            }
        }



        return [
            'code' => '1',
            'message' => '结佣成功'
        ];

    }


    /**
     * 转介提成
     * @param array $agentInfo 转介人信息
     * @param array $toAgentInfo 接收人信息
     * @param array $buildingPoint 该楼盘所有的点位
     * @param string $amount   房款最终成交金额
     * @return array
     */
    public function transfer($agentInfo,$toAgentInfo,$buildingPoint,$amount){
        //获取成交经纪人的所有上级
        $higher = [];
        $check = $agentInfo;
        while($check){
            $check = $check->higher;
            if ($check)
                $higher[] = \app\common\model\Account::field('id,role')->find($check['a_id'])->toArray();
        }

        foreach ($higher as $value){
            //一级渠道
            if (in_array($value['role'],['30','21','15'])){
                $step1 = $value['id'];
            }
            //二级渠道
            elseif ($value['role'] =='24'){
                $step2 = $value['id'];
                $point = $this -> point($buildingPoint,'action',2);
                if ($point)
                    $step2 = [
                        'account_id' => $value['id'],
                        'count' => $point[1]=='%'?$amount*$point[0]*0.01:$point[0],
                    ];
            }
            //获取自拓经理/推广经理的成交价格
            elseif (in_array($value['role'],['17','18'])){
                $point = $this -> point($buildingPoint,'role',$value['role']);
                if ($point)
                    $addData[] = [
                        'account_id' => $value['id'],
                        'count' => $point[1]=='%'?$amount*$point[0]*0.01:$point[0],
                        'description' => '转介成交提成'
                    ];
                break;
            }
        }

        //代理
        if (!$step1){
            //如果是自拓客服/推广客服走楼盘点位
            if(in_array($agentInfo['role'],['31','32'])){
                $point = $this -> point($buildingPoint,'role',$agentInfo['role']);
                if ($point)
                    $addData[] = [
                        'account_id' => $agentInfo['id'],
                        'count' => $point[1]=='%'?$amount*$point[0]*0.01:$point[0],
                        'description' => '转介成交提成'
                    ];
            }
            //走楼盘转接费
            else{
                $point = $this -> point($buildingPoint,'action','5');
                if ($point)
                    $addData[] = [
                        'account_id' => $agentInfo['id'],
                        'count' => $point[1]=='%'?$amount*$point[0]*0.01:$point[0],
                        'description' => '转介成交提成'
                    ];
            }
        }
        //渠道
        else{
            //判断对方是否是房金/罗宅
            if (in_array($toAgentInfo['role'],['21','30'])){
                //算二级渠道转介费
                $point = $this -> point($buildingPoint,'action',2);
                if ($point)
                    $addData[] = [
                        'account_id' => $step1,
                        'count' => $point[1]=='%'?$amount*$point[0]*0.01:$point[0],
                        'description' => '二级渠道转介费'
                    ];
            }
            //算一级渠道转介费/二级渠道
            else{

                //二级渠道
                $point = $this -> point($buildingPoint,'action',1);
                if ($point)
                    $count1 = $point[1]=='%'?$amount*$point[0]*0.01:$point[0];
                if($step2){
                    $point = $this -> point($buildingPoint,'action',2);
                    if ($point){
                        $count2 = $point[1]=='%'?$amount*$point[0]*0.01:$point[0];
                        $addData[] = [
                            'account_id' => $step2,
                            'count' => $count2,
                            'description' => '二级渠道转介费'
                        ];

                        if ($count1){
                            $count1 -= $count2;
                            if ($count1<0)
                                $count1 = '';
                        }

                    }
                }

                //一级渠道
                if ($count1)
                    $addData[] = [
                        'account_id' => $step1,
                        'count' => $count1,
                        'description' => '一级渠道转介费'
                    ];
            }
        }

        return $addData;
    }

    public function dels(){
        $id = input('id');
        \app\common\model\Message::where('id', $id)
            ->update([
                'status' => '跟进中',
            ]);
        return [
            'code' => '1',
            'message' => '取消成功'
        ];
    }

    //获取楼盘点位
    protected function point($buildingPoint,$role,$role_id){
        foreach ($buildingPoint as $value){
            if ($value[$role] == $role_id){
                $point = explode(',',$value['point']);
                break;
            }
        }
        if ($point)
            if ($point[0] != 0)
                return $point;
        return '';
    }
}